import { useGetArticleAction, useUpdateArticleAction } from '@/services/action';
import { useGetAbout, useGetOneArticle, useGetTopN } from '@/services/article';
import { useAddAttention, useDeleteAttention } from '@/services/attention';
import { useGetAllCommentByAid } from '@/services/comment';
import QUERY_KEYS from '@/services/constant';
import { ARTICLES_SOURCE } from '@/services/constant/articles';
import {
  EyeOutlined,
  StarOutlined,
  LikeOutlined,
  MessageOutlined,
} from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { history, styled, useIntl, useModel } from '@umijs/max';
import { useSearchParams } from '@umijs/max';
import { Layout, Space, Spin, Tag, Typography } from 'antd';
import { Content } from 'antd/es/layout/layout';
import Sider from 'antd/es/layout/Sider';
import { useEffect, useState } from 'react';
import { IconText } from '../dashboard/my-articles';
import ActionList from './components/ActionList';
import CommentList from './components/CommentList';
import { OneRowText } from './style';

const contentStyle: React.CSSProperties = {
  textAlign: 'center',
  minHeight: 120,
  lineHeight: '120px',
  color: '#fff',
  minWidth: '700px',
  // backgroundColor: '#108ee9',
};

const siderStyle: React.CSSProperties = {
  textAlign: 'center',
  lineHeight: '120px',
  color: '#fff',
  marginLeft: '20px',
  backgroundColor: 'transparent',
};

const StyledSider = styled(Sider)`
  .ant-pro-card-title {
    font-size: 30px;
  }
`;

const { Title, Paragraph, Text } = Typography;

const articleSourceList = ARTICLES_SOURCE;

const Article: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const intl = useIntl();
  const [searchParams] = useSearchParams();
  const [realAction, setRealAction] = useState<API.IArticleAction>({
    islike: 0,
    star: 0,
    attention: 0,
  });
  const [commentList, setCommentList] = useState<CommentType[]>([]);
  const { isLoading, data: res } = useGetOneArticle(
    parseInt(searchParams.get('id') ?? '-1'),
  );
  const { data: commentRes } = useGetAllCommentByAid(
    parseInt(searchParams.get('id') ?? '-1'),
    initialState?.id ?? -1,
  );
  const { data: articleActionRes } = useGetArticleAction(
    initialState?.id ?? -1,
    parseInt(searchParams.get('id') ?? '-1'),
  );
  const { mutateAsync: updateArticleAction } = useUpdateArticleAction(
    QUERY_KEYS.ARTICLE_ACTION_GET,
  );
  const { mutateAsync: addAttention } = useAddAttention(
    QUERY_KEYS.ARTICLE_ACTION_GET,
  );
  const { mutateAsync: deleteAttention } = useDeleteAttention(
    QUERY_KEYS.ARTICLE_ACTION_GET,
  );
  const { data: top10 } = useGetTopN(10);
  const { data: aboutData } = useGetAbout(
    res?.data.isNews === 1 ? 0 : res?.data.isQuestion === 1 ? 1 : 2,
  );

  const updateAction = (action: TAction, curVal: number) => {
    if (action === 'attention') {
      if (curVal === -1)
        addAttention({
          accountId: initialState?.id,
          otherAccountId: realAction.otherAccountId,
        });
      else deleteAttention(realAction.attId ?? -1);
    } else {
      const obj: API.IArticleAction = {
        accountId: initialState?.id,
        articleId: parseInt(searchParams.get('id') ?? '-1'),
        star: action === 'star' ? (curVal === 1 ? 0 : 1) : realAction.star,
        islike: action === 'zan' ? (curVal === 1 ? 0 : 1) : realAction.islike,
      };
      if (action === 'cai') obj.islike = curVal === 2 ? 0 : 2;
      if (realAction.id) obj.id = realAction.id;
      updateArticleAction(obj);
    }
  };

  useEffect(() => {
    if (articleActionRes && articleActionRes.code === 200) {
      if (articleActionRes.data.length > 0)
        setRealAction(articleActionRes.data[0]);
      else
        updateArticleAction({
          accountId: initialState?.id,
          articleId: parseInt(searchParams.get('id') ?? '-1'),
          look: 1,
        });
    }
  }, [articleActionRes]);

  useEffect(() => {
    if (commentRes && commentRes.code === 200) {
      setCommentList(commentRes.data);
    }
  }, [commentRes]);

  return (
    <>
      {isLoading ? (
        <Spin tip="Loading..." size="large">
          <div style={{ height: '800px' }}></div>
        </Spin>
      ) : (
        <Layout>
          <Content style={contentStyle}>
            {res?.data.isQuestion === 1 ? (
              <ProCard
                title={
                  <span>
                    <strong>问题：</strong>
                    {res?.data.title}
                  </span>
                }
                extra={
                  <Space>
                    <span>提问人： {res?.data.nickName}</span>
                    <span>提问时间： {res?.data.time.substring(0, 10)}</span>
                  </Space>
                }
              >
                <Paragraph style={{ textAlign: 'left' }}>
                  <strong>简介：</strong>
                  {res?.data.introduction ?? '无'}
                </Paragraph>
                {/* ql-editor这个类名不能省 */}
                <Paragraph>
                  <div
                    dangerouslySetInnerHTML={{
                      __html: res?.data.content ?? '',
                    }}
                    className="ql-editor"
                  ></div>
                </Paragraph>
              </ProCard>
            ) : (
              <ProCard
                extra={
                  <Space>
                    <IconText
                      icon={EyeOutlined}
                      text={(res?.data.lookNum ?? 0) + ''}
                      key="list-vertical-eye"
                    />
                    <IconText
                      icon={StarOutlined}
                      text={(res?.data.starNum ?? 0) + ''}
                      key="list-vertical-star"
                    />
                    <IconText
                      icon={LikeOutlined}
                      text={(res?.data.likeNum ?? 0) + ''}
                      key="list-vertical-like"
                    />
                    <IconText
                      icon={MessageOutlined}
                      text={(res?.data.commentNum ?? 0) + ''}
                      key="list-vertical-message"
                    />
                  </Space>
                }
              >
                <Typography>
                  <Title> {res?.data.title}</Title>
                  <Title level={5}>
                    <Space>
                      <Text mark>{res?.data.nickName}</Text>
                      <Text mark>
                        {res &&
                          intl.formatMessage({
                            id: `article.articleSource.${
                              articleSourceList[res.data.articleSource]
                            }`,
                          })}
                      </Text>
                      <Text mark>{res?.data.time.substring(0, 10)}</Text>
                    </Space>
                  </Title>
                  <Space direction="vertical">
                    <Text>
                      标签：
                      {res?.data.tags
                        ?.split('/')
                        .map((tag: string, index: number) => (
                          <Tag key={index}>{tag}</Tag>
                        ))}
                    </Text>
                    <Text code>简介：{res?.data.introduction}</Text>
                  </Space>
                  {/* ql-editor这个类名不能省 */}
                  <Paragraph>
                    <div
                      dangerouslySetInnerHTML={{
                        __html: res?.data.content ?? '',
                      }}
                      className="ql-editor"
                    ></div>
                  </Paragraph>
                </Typography>
              </ProCard>
            )}
            <ActionList
              callBack={(a, c) => updateAction(a, c)}
              data={realAction}
              aid={res?.data.id ?? -1}
            ></ActionList>
            {commentList.length > 0 ? (
              <CommentList data={commentList}></CommentList>
            ) : (
              ''
            )}
          </Content>

          <StyledSider style={siderStyle} width={400}>
            <Space style={{ width: '100%' }} direction="vertical">
              <ProCard title="相关推荐">
                {aboutData?.data &&
                  aboutData?.data.map((item) =>
                    res?.data.id !== item.id ? (
                      <OneRowText
                        onClick={() => history.push(`/article?id=${item.id}`)}
                      >
                        {item.title}
                      </OneRowText>
                    ) : (
                      ''
                    ),
                  )}
              </ProCard>
              <ProCard title="最近更新">
                {top10?.data &&
                  top10?.data.map((item) =>
                    res?.data.id !== item.id ? (
                      <OneRowText
                        onClick={() => history.push(`/article?id=${item.id}`)}
                      >
                        <Tag style={{ display: 'inline-block' }}>
                          {item.isNews === 1
                            ? '咨讯'
                            : item.isQuestion === 1
                            ? '问答'
                            : '文章'}
                        </Tag>
                        {item.title}
                      </OneRowText>
                    ) : (
                      ''
                    ),
                  )}
              </ProCard>
            </Space>
          </StyledSider>
        </Layout>
      )}
    </>
  );
};

export default Article;
